import React, { useState } from 'react';
import MonacoEditor from 'react-monaco-editor';
import axios from 'axios';

const CodeEditor = () => {
  const [code, setCode] = useState('');

  const handleEditorChange = (newValue) => {
    setCode(newValue);
  };
  // 保存按钮
  const saveCode = async () => {
    console.log('Saved Code:', code);
    try {
      const response = await axios.post('http://localhost:3000/api/code/save', {
        userId: '123456', // 示例用户 ID
        code: code,
      });
      alert('Code saved successfully');
    } catch (error) {
      console.error('Error saving code:', error);
      alert('Failed to save code');
    }
  };
  // 清除按钮
  const clearCode = () => {
    setCode('');
  };
  // 修改保存功能，将代码发送到后端

  return (
    <div>
      <h2>Code Editor</h2>
      <button onClick={clearCode}>Clear Code</button>
      <button onClick={saveCode}>Save Code</button>
      <MonacoEditor
        width="800"
        height="600"
        language="javascript"
        theme="vs-dark"
        value={code}
        onChange={handleEditorChange}
      />

    </div>
  );
};

export default CodeEditor;
